import React, {useEffect, useState, forwardRef, useImperativeHandle, useMemo} from 'react';
import PageModule from "@/components/PageModule.tsx";
import {Form, Row, Table, Button, message} from "antd";
import CycleForm from "@/components/DynamicSearchForm/CycleForm.tsx";
import PageActionBar from "@/components/PageActionBar.tsx";
import {findDicNameForDicCode, getDicOnCode} from "@/utils/dicAll.ts";
import {onlyNumberLast2Digits} from "@/utils/regular.ts";
import {querySaleListForProject} from "@/axios/apis.ts";

const TypesInsurance = forwardRef(({carRiskInfo, policyDisabled}, ref) => {
    useImperativeHandle(ref, () => ({
        verifyTheForm: () => {
            setShow(false)
            if (!dataSource.length) {
                message.warning('险种信息最少一条')
                return false
            }
            return dataSource
        }
    }))
    const [RiskForm] = Form.useForm()
    const [rowIndex, setRowIndex] = useState(undefined)
    const [dataSource, setDataSource] = useState([])
    const [formDisabled, setFormDisablede] = useState(false)
    const btnList = [
        {
            name: '新增',
            type: 'primary',
            onClick: () => {
                setShow(true)
                // let code = getPojectCode()
                //  console.log(code,'code')
            }
        }
    ]
    const columns = [
        {
            title: '操作',
            key: 'action',
            render: (_, record, index) => (
                <div className="table-options">
                    <span className="operation_style"
                          onClick={() => lookOrEdit('details', record, undefined)}>查看</span>
                    {!policyDisabled?<template>
                        <span className="operation_style" onClick={() => lookOrEdit('edit', record, index)}>修改</span>
                        <span className="operation_style danger" onClick={() => deleteRow(index)}>删除</span>
                    </template>:null}
                </div>
            ),
            width: 140,
            align: 'center'
        },
        {title: '险种名称', dataIndex: 'riskName', key: 'riskName'},
        {title: '险种代码', dataIndex: 'riskCode', key: 'riskCode'},
        {title: '保费（元）', dataIndex: 'prem', key: 'prem'},
        {title: '保额（元）', dataIndex: 'amount', key: 'amount'},
        {title: '保险期间（年）', dataIndex: 'ensurePeriod', key: 'ensurePeriod'},
        {title: '车船税（元）', dataIndex: 'vehicleAndVesselTax', key: 'vehicleAndVesselTax'},
        {
            title: '险种状态', dataIndex: 'riskState', key: 'riskState',
            render: (value) => <>{findDicNameForDicCode('SYS.VALID', value)}</>,
        },
    ]
    const [formFields, setFormFields] = useState([
        {
            type: 'select',
            name: 'riskCode',
            label: '险种名称',
            placeholder: '请选择',
            options: getDicOnCode('PRODUCT.CARRISKTYPE'),
            rules: [{required: true, message: '请选择险种名称'}],
        },
        {
            type: 'input',
            name: 'prem',
            label: '保费（元）',
            rules: [{required: true, message: '请输入保费'}, {validator: onlyNumberLast2Digits}],
        },
        {
            type: 'input',
            name: 'amount',
            label: '保额（元）',
            rules: [{validator: onlyNumberLast2Digits}]
        },
        {
            type: 'input',
            name: 'ensurePeriod',
            label: '保险期间（年）',
            rules: [{validator: onlyNumberLast2Digits}]
        },
        {
            type: 'input',
            name: 'vehicleAndVesselTax',
            label: '车船税（元）',
            rules: [{required: true, message: '请输入车船税'}, {validator: onlyNumberLast2Digits}],
        }
    ])
    const [show, setShow] = useState(false)
    // 查看修改
    const lookOrEdit = (type, record, index): void => {
        setRowIndex(index)
        RiskForm.setFieldsValue(record)
        setShow(true)
        setFormDisablede(type === 'details')
    }
    // 删除
    const deleteRow = (index: number) => {
        setDataSource(dataSource.filter((_, i) => i !== index))
    }
    const cancel = () => {
        setShow(false)
        RiskForm.resetFields()
        setFormDisablede(false)
    }
    const onFinish = (values: any) => {
        console.log('Success:', values);
        const item = formFields[0].options.find(ite => ite.dicItemCode === values.riskCode)
        if (item) {
            values = {...values, riskName: item.dicItemName}
        }
        if (rowIndex !== undefined) {
            const list = [...dataSource]
            list[rowIndex] = values
            setDataSource(list)
        } else {
            setDataSource([...dataSource, values]);
        }
        setShow(false)
        RiskForm.resetFields()
    }
    useEffect(() => {
        if (!carRiskInfo || !carRiskInfo.length) return
        setDataSource(carRiskInfo)
    }, [carRiskInfo])
    return (
        <div className="mt20">
            <PageModule title="险种信息" btns={!policyDisabled?<PageActionBar btnList={btnList} inline />:null}>
                <Table dataSource={dataSource} columns={columns} bordered={true} size="middle" pagination={false} />
                <Form
                    layout="horizontal"
                    autoComplete="off"
                    labelCol={{span: 8}}
                    wrapperCol={{span: 16}}
                    form={RiskForm}
                    style={{marginTop: 20, display: show ? 'block' : 'none'}}
                    onFinish={onFinish}
                    initialValues={
                        {countryCode: '008zg'}
                    }
                    disabled={formDisabled}
                >
                    <Row>
                        <CycleForm fields={formFields} />
                    </Row>
                    <Form.Item wrapperCol={{offset: 2}}>
                        <Button className="mr15" type="primary" htmlType="submit">保存</Button>
                        <Button onClick={cancel} disabled={false}>取消</Button>
                    </Form.Item>
                </Form>
            </PageModule>
        </div>
    );
})
export default TypesInsurance;